class Solution {
public:
    int romanToInt(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        map<string, int> romanMap;
        romanMap["I"] = 1;
        romanMap["V"] = 5;
        romanMap["X"] = 10;
        romanMap["L"] = 50;
        romanMap["C"] = 100;
        romanMap["D"] = 500;
        romanMap["M"] = 1000;

        romanMap["IV"] = 4;
        romanMap["IX"] = 9;
        romanMap["XL"] = 40;
        romanMap["XC"] = 90;
        romanMap["CD"] = 400;
        romanMap["CM"] = 900;

        int n = s.length();
        int ans = 0;

        for (int i = 0; i < n; ) {
            if (i == n - 1 ||
                romanMap[s.substr(i, 1)] >= romanMap[s.substr(i + 1, 1)]) {
                ans += romanMap[s.substr(i, 1)];
                ++i;
            } else {
                ans += romanMap[s.substr(i, 2)];
                i += 2;
            }
        }
        return ans;
    }
};
